package com.work.music.utils;

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;


/**
 * Created by z02464 on 2016/8/17.
 */
public class StringMng {
    
    /**
     * 生成MD5摘要值
     */
    public static String MD5Util(String ps){

        if(null != ps){

            String md5str = "";
            try{
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(ps.getBytes());
                byte[] results = md.digest();

                md5str = bytesToHex(results);

            }catch (Exception ex){

            }
            return md5str;
        }
        return null;
    }

    /**
     * 二进制转十六进制
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        //把数组每一字节换成16进制连成md5字符串
        int digital;
        for (byte aByte : bytes) {
            digital = aByte;

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString();
    }

    /**
     * Base64编码
     */
    /**
     * @apiNote 将字符串进行BASE64编码
     */
    public static String getBase64(String s) {
        if (s == null) return null;
        try {
            return (new BASE64Encoder()).encode( s.getBytes("UTF-8") );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
